<!--
  试卷编辑器
  支持手动组卷和智能组卷功能
-->
<template>
  <div class="paper-editor">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="goBack" text>返回</el-button>
        <h2>{{ isEdit ? '编辑试卷' : '创建试卷' }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="handlePreview" :icon="View">预览</el-button>
        <el-button @click="saveDraft" :loading="saving">保存草稿</el-button>
        <el-button type="primary" @click="publishPaper" :loading="saving">
          {{ isEdit ? '更新试卷' : '发布试卷' }}
        </el-button>
      </div>
    </div>

    <!-- 编辑器布局 -->
    <div class="editor-layout">
      <!-- 左侧配置面板 -->
      <div class="config-panel">
        <el-card class="basic-info">
          <template #header>
            <span>基本信息</span>
          </template>

          <el-form
            ref="basicFormRef"
            :model="paperForm"
            :rules="basicRules"
            label-width="80px"
            size="small"
          >
            <el-form-item label="试卷标题" prop="title">
              <el-input
                v-model="paperForm.title"
                placeholder="请输入试卷标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="试卷描述" prop="description">
              <el-input
                v-model="paperForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入试卷描述"
                maxlength="300"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="试卷类型" prop="paper_type">
              <el-select v-model="paperForm.paper_type" style="width: 100%">
                <el-option label="常规试卷" value="regular" />
                <el-option label="智能组卷" value="smart" />
                <el-option label="随机试卷" value="random" />
              </el-select>
            </el-form-item>

            <el-form-item label="总分" prop="total_score">
              <el-input-number
                v-model="paperForm.total_score"
                :min="10"
                :max="1000"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="及格分" prop="passing_score">
              <el-input-number
                v-model="paperForm.passing_score"
                :min="0"
                :max="paperForm.total_score"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="时长" prop="duration">
              <el-input-number
                v-model="paperForm.duration"
                :min="5"
                :max="480"
                style="width: 100%"
              />
              <div class="form-unit">分钟</div>
            </el-form-item>

            <el-form-item label="标签">
              <el-select
                v-model="paperForm.tags"
                multiple
                filterable
                allow-create
                placeholder="添加标签"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in commonTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 组卷方式 -->
        <el-card class="assembly-method">
          <template #header>
            <span>组卷方式</span>
          </template>

          <el-radio-group v-model="assemblyMethod" @change="handleMethodChange">
            <el-radio value="manual">
              <div class="method-option">
                <div class="method-title">手动组卷</div>
                <div class="method-desc">从题库中手动选择题目</div>
              </div>
            </el-radio>
            <el-radio value="smart">
              <div class="method-option">
                <div class="method-title">智能组卷</div>
                <div class="method-desc">AI智能生成试卷</div>
              </div>
            </el-radio>
            <el-radio value="template">
              <div class="method-option">
                <div class="method-title">模板组卷</div>
                <div class="method-desc">基于已有模板创建</div>
              </div>
            </el-radio>
          </el-radio-group>
        </el-card>

        <!-- 手动组卷配置 -->
        <el-card v-if="assemblyMethod === 'manual'" class="manual-config">
          <template #header>
            <span>题目筛选</span>
          </template>

          <el-form :model="questionFilter" size="small">
            <el-form-item label="题库">
              <el-select
                v-model="questionFilter.question_bank"
                placeholder="选择题库"
                clearable
                style="width: 100%"
                @change="filterQuestions"
              >
                <el-option
                  v-for="bank in questionBanks"
                  :key="bank.id"
                  :label="bank.name"
                  :value="bank.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="题型">
              <el-select
                v-model="questionFilter.question_type"
                placeholder="选择题型"
                clearable
                style="width: 100%"
                @change="filterQuestions"
              >
                <el-option label="单选题" value="single_choice" />
                <el-option label="多选题" value="multiple_choice" />
                <el-option label="判断题" value="true_false" />
                <el-option label="填空题" value="fill_blank" />
                <el-option label="简答题" value="short_answer" />
                <el-option label="编程题" value="programming" />
              </el-select>
            </el-form-item>

            <el-form-item label="难度">
              <el-select
                v-model="questionFilter.difficulty"
                placeholder="选择难度"
                clearable
                style="width: 100%"
                @change="filterQuestions"
              >
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="filterQuestions" style="width: 100%">
                筛选题目
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 统计信息 -->
          <div class="question-stats">
            <div class="stat-item">
              <span class="stat-label">已选题目:</span>
              <span class="stat-value">{{ selectedQuestions.length }} 道</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">当前总分:</span>
              <span class="stat-value">{{ currentTotalScore }} 分</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">目标总分:</span>
              <span class="stat-value">{{ paperForm.total_score }} 分</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">完成度:</span>
              <el-progress
                :percentage="completionPercentage"
                :color="getProgressColor(completionPercentage)"
                :show-text="false"
                style="width: 80px"
              />
              <span class="stat-value">{{ completionPercentage }}%</span>
            </div>
          </div>
        </el-card>

        <!-- 智能组卷配置 -->
        <el-card v-else-if="assemblyMethod === 'smart'" class="smart-config">
          <template #header>
            <span>智能组卷配置</span>
          </template>

          <el-form :model="smartConfig" size="small">
            <el-form-item label="题库" required>
              <el-select v-model="smartConfig.question_bank" style="width: 100%">
                <el-option
                  v-for="bank in questionBanks"
                  :key="bank.id"
                  :label="bank.name"
                  :value="bank.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="题目数量" required>
              <el-input-number
                v-model="smartConfig.question_count"
                :min="1"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="难度分布">
              <div class="difficulty-dist">
                <div class="dist-item">
                  <span>简单:</span>
                  <el-input-number
                    v-model="smartConfig.easy_count"
                    :min="0"
                    size="small"
                  />
                </div>
                <div class="dist-item">
                  <span>中等:</span>
                  <el-input-number
                    v-model="smartConfig.medium_count"
                    :min="0"
                    size="small"
                  />
                </div>
                <div class="dist-item">
                  <span>困难:</span>
                  <el-input-number
                    v-model="smartConfig.hard_count"
                    :min="0"
                    size="small"
                  />
                </div>
              </div>
            </el-form-item>

            <el-form-item label="知识点">
              <el-select
                v-model="smartConfig.knowledge_points"
                multiple
                filterable
                placeholder="选择知识点"
                style="width: 100%"
              >
                <el-option
                  v-for="kp in knowledgePoints"
                  :key="kp"
                  :label="kp"
                  :value="kp"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="generateSmartPaper"
                :loading="generating"
                style="width: 100%"
              >
                {{ generating ? '生成中...' : '开始智能组卷' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 模板组卷配置 -->
        <el-card v-else-if="assemblyMethod === 'template'" class="template-config">
          <template #header>
            <span>选择模板</span>
          </template>

          <el-empty description="模板组卷功能开发中..." />
        </el-card>
      </div>

      <!-- 中间题目选择区域 -->
      <div class="question-selector">
        <el-card class="selector-header">
          <template #header>
            <div class="selector-title">
              <span>题库题目</span>
              <el-badge :value="filteredQuestions.length" :max="99" type="primary">
                <el-icon><Document /></el-icon>
              </el-badge>
            </div>
          </template>

          <el-input
            v-model="searchKeyword"
            placeholder="搜索题目内容..."
            :prefix-icon="Search"
            @input="searchQuestions"
            clearable
          />

          <div v-loading="loading" class="question-list">
            <div
              v-for="question in paginatedQuestions"
              :key="question.id"
              class="question-item"
              :class="{ selected: isQuestionSelected(question.id) }"
              @click="toggleQuestion(question)"
            >
              <div class="question-header">
                <span class="question-type">{{ getTypeText(question.question_type) }}</span>
                <span class="question-difficulty" :class="question.difficulty">
                  {{ getDifficultyText(question.difficulty) }}
                </span>
                <el-checkbox
                  :checked="isQuestionSelected(question.id)"
                  @change="toggleQuestion(question)"
                  @click.stop
                />
              </div>

              <div class="question-content">
                {{ truncateText(stripHtml(question.content), 80) }}
              </div>

              <div class="question-footer">
                <span class="question-points">{{ question.points || 5 }}分</span>
                <div class="question-tags" v-if="question.tags?.length">
                  <el-tag
                    v-for="tag in question.tags.slice(0, 2)"
                    :key="tag"
                    size="small"
                    type="info"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination-wrapper" v-if="totalQuestions > pageSize">
              <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :total="totalQuestions"
                layout="prev, pager, next"
                small
                @current-change="handlePageChange"
              />
            </div>

            <el-empty v-if="filteredQuestions.length === 0 && !loading" description="没有找到相关题目" />
          </div>
        </el-card>
      </div>

      <!-- 右侧试卷预览 -->
      <div class="paper-preview">
        <el-card class="preview-header">
          <template #header>
            <div class="preview-title">
              <span>试卷预览</span>
              <el-button
                text
                :icon="Refresh"
                @click="refreshPreview"
                size="small"
              >
                刷新
              </el-button>
            </div>
          </template>

          <div class="paper-content">
            <!-- 试卷信息 -->
            <div class="paper-info">
              <h3>{{ paperForm.title || '试卷标题' }}</h3>
              <p>{{ paperForm.description || '试卷描述' }}</p>
              <div class="paper-meta">
                <span class="meta-item">
                  <el-icon><Clock /></el-icon>
                  {{ paperForm.duration }}分钟
                </span>
                <span class="meta-item">
                  <el-icon><Document /></el-icon>
                  {{ selectedQuestions.length }}题
                </span>
                <span class="meta-item">
                  <el-icon><TrendCharts /></el-icon>
                  {{ currentTotalScore }}分
                </span>
              </div>
            </div>

            <!-- 题目列表 -->
            <div class="paper-questions">
              <draggable
                v-model="selectedQuestions"
                item-key="id"
                @end="handleQuestionOrder"
                class="questions-container"
              >
                <template #item="{ element: question, index }">
                  <div class="paper-question">
                    <div class="question-number">{{ index + 1 }}.</div>
                    <div class="question-details">
                      <div class="question-header-preview">
                        <span class="question-type">{{ getTypeText(question.question_type) }}</span>
                        <div class="question-actions">
                          <el-button
                            text
                            :icon="Edit"
                            size="small"
                            @click="editQuestion(question)"
                          />
                          <el-button
                            text
                            :icon="Delete"
                            size="small"
                            type="danger"
                            @click="removeQuestion(question.id)"
                          />
                          <el-icon class="drag-handle"><Rank /></el-icon>
                        </div>
                      </div>
                      <div class="question-content-preview">
                        {{ truncateText(stripHtml(question.content), 100) }}
                      </div>
                      <div class="question-meta-preview">
                        <span class="meta-tag difficulty" :class="question.difficulty">
                          {{ getDifficultyText(question.difficulty) }}
                        </span>
                        <span class="meta-tag points">{{ question.points || 5 }}分</span>
                      </div>
                    </div>
                  </div>
                </template>
              </draggable>

              <el-empty v-if="selectedQuestions.length === 0" description="暂无题目，请从左侧选择" />
            </div>

            <!-- 操作按钮 -->
            <div class="preview-actions">
              <el-button
                type="primary"
                :icon="MagicStick"
                @click="enhancePaper"
                :loading="enhancing"
                style="width: 100%"
              >
                {{ enhancing ? '优化中...' : 'AI优化试卷' }}
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      title="试卷预览"
      width="900px"
    >
      <div class="preview-dialog-content">
        <!-- 预览内容 -->
        <div class="preview-paper">
          <div class="preview-header">
            <h2>{{ paperForm.title }}</h2>
            <p class="preview-description">{{ paperForm.description }}</p>
            <div class="preview-instructions">
              <p><strong>考试说明：</strong></p>
              <ul>
                <li>考试时间：{{ paperForm.duration }}分钟</li>
                <li>试卷总分：{{ currentTotalScore }}分</li>
                <li>及格分数：{{ paperForm.passing_score }}分</li>
                <li>题目数量：{{ selectedQuestions.length }}道</li>
              </ul>
            </div>
          </div>

          <div class="preview-questions">
            <div
              v-for="(question, index) in selectedQuestions"
              :key="question.id"
              class="preview-question"
            >
              <div class="question-title">
                {{ index + 1 }}. {{ getTypeText(question.question_type) }} ({{ question.points || 5 }}分)
              </div>
              <div class="question-text" v-html="question.content" />

              <!-- 选择题选项 -->
              <div
                v-if="['single_choice', 'multiple_choice'].includes(question.question_type)"
                class="question-options"
              >
                <div
                  v-for="(option, optIndex) in question.options || []"
                  :key="optIndex"
                  class="option-item"
                >
                  {{ String.fromCharCode(65 + optIndex) }}. {{ option }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  ArrowLeft,
  View,
  Document,
  Search,
  Refresh,
  Edit,
  Delete,
  Clock,
  TrendCharts,
  MagicStick,
  Rank
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { questionApi } from '@/api/questions'
import { examPaperApi } from '@/api/examPaper'
import { aiApi } from '@/api/ai'
import { useAuthStore } from '@/stores'
import type { Question, QuestionBank, ExamPaper } from '@/types'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const basicFormRef = ref<FormInstance>()
const saving = ref(false)
const loading = ref(false)
const generating = ref(false)
const enhancing = ref(false)
const showPreviewDialog = ref(false)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 组卷方式
const assemblyMethod = ref('manual')

// 表单数据
const paperForm = reactive({
  title: '',
  description: '',
  paper_type: 'regular',
  total_score: 100,
  passing_score: 60,
  duration: 120,
  tags: [] as string[]
})

// 题目筛选
const questionFilter = reactive({
  question_bank: '',
  question_type: '',
  difficulty: ''
})

// 智能组卷配置
const smartConfig = reactive({
  question_bank: '',
  question_count: 20,
  easy_count: 6,
  medium_count: 10,
  hard_count: 4,
  knowledge_points: [] as string[]
})

// 数据列表
const questionBanks = ref<QuestionBank[]>([])
const allQuestions = ref<Question[]>([])
const filteredQuestions = ref<Question[]>([])
const selectedQuestions = ref<Question[]>([])
const knowledgePoints = ref<string[]>([])

// 搜索和分页
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalQuestions = ref(0)

// 常用标签
const commonTags = ['期末考试', '期中考试', '单元测试', '模拟考试', '随堂测验']

// 表单验证规则
const basicRules: FormRules = {
  title: [
    { required: true, message: '请输入试卷标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  paper_type: [
    { required: true, message: '请选择试卷类型', trigger: 'change' }
  ],
  total_score: [
    { required: true, message: '请设置总分', trigger: 'change' },
    { type: 'number', min: 10, max: 1000, message: '总分在10-1000之间', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请设置考试时长', trigger: 'change' },
    { type: 'number', min: 5, max: 480, message: '时长在5-480分钟之间', trigger: 'blur' }
  ]
}

// 计算属性
const paginatedQuestions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredQuestions.value.slice(start, end)
})

const currentTotalScore = computed(() => {
  return selectedQuestions.value.reduce((total, question) => {
    return total + (question.points || 5)
  }, 0)
})

const completionPercentage = computed(() => {
  if (paperForm.total_score === 0) return 0
  return Math.min(Math.round((currentTotalScore.value / paperForm.total_score) * 100), 100)
})

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 50) return '#f56c6c'
  if (percentage < 80) return '#e6a23c'
  return '#67c23a'
}

// 工具函数
const stripHtml = (html: string) => {
  return html.replace(/<[^>]*>/g, '')
}

const truncateText = (text: string, maxLength: number) => {
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

const getTypeText = (type: string) => {
  const types: Record<string, string> = {
    single_choice: '单选',
    multiple_choice: '多选',
    true_false: '判断',
    fill_blank: '填空',
    short_answer: '简答',
    programming: '编程'
  }
  return types[type] || type
}

const getDifficultyText = (difficulty: string) => {
  const texts: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return texts[difficulty] || difficulty
}

// 加载题库和题目
const loadQuestionBanks = async () => {
  try {
    const response = await questionApi.getQuestionBanks({ page_size: 100 })
    questionBanks.value = response.data.results
  } catch (error) {
    console.error('Failed to load question banks:', error)
  }
}

const loadQuestions = async () => {
  try {
    loading.value = true
    const response = await questionApi.getQuestions({
      page_size: 1000,
      is_active: true
    })
    allQuestions.value = response.data.results
    filteredQuestions.value = allQuestions.value
    totalQuestions.value = filteredQuestions.value.length

    // 提取知识点
    const tags = new Set<string>()
    allQuestions.value.forEach(q => {
      q.tags?.forEach(tag => tags.add(tag))
    })
    knowledgePoints.value = Array.from(tags)
  } catch (error) {
    console.error('Failed to load questions:', error)
    ElMessage.error('加载题目失败')
  } finally {
    loading.value = false
  }
}

// 筛选题目
const filterQuestions = () => {
  let filtered = [...allQuestions.value]

  if (questionFilter.question_bank) {
    filtered = filtered.filter(q => q.question_bank === questionFilter.question_bank)
  }

  if (questionFilter.question_type) {
    filtered = filtered.filter(q => q.question_type === questionFilter.question_type)
  }

  if (questionFilter.difficulty) {
    filtered = filtered.filter(q => q.difficulty === questionFilter.difficulty)
  }

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(q =>
      stripHtml(q.content).toLowerCase().includes(keyword) ||
      q.title.toLowerCase().includes(keyword)
    )
  }

  filteredQuestions.value = filtered
  totalQuestions.value = filtered.length
  currentPage.value = 1
}

// 搜索题目
const searchQuestions = () => {
  filterQuestions()
}

// 题目选择
const isQuestionSelected = (questionId: number) => {
  return selectedQuestions.value.some(q => q.id === questionId)
}

const toggleQuestion = (question: Question) => {
  const index = selectedQuestions.value.findIndex(q => q.id === question.id)
  if (index > -1) {
    selectedQuestions.value.splice(index, 1)
  } else {
    selectedQuestions.value.push({
      ...question,
      points: question.points || 5
    })
  }
}

const removeQuestion = (questionId: number) => {
  const index = selectedQuestions.value.findIndex(q => q.id === questionId)
  if (index > -1) {
    selectedQuestions.value.splice(index, 1)
  }
}

// 题目拖拽排序
const handleQuestionOrder = () => {
  // 题目顺序已通过 v-model 自动更新
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
}

// 处理组卷方式变化
const handleMethodChange = (method: string) => {
  if (method === 'manual') {
    filterQuestions()
  }
}

// 智能组卷
const generateSmartPaper = async () => {
  try {
    generating.value = true

    if (!smartConfig.question_bank) {
      ElMessage.warning('请选择题库')
      return
    }

    const totalCount = smartConfig.easy_count + smartConfig.medium_count + smartConfig.hard_count
    if (totalCount === 0) {
      ElMessage.warning('请设置题目数量分布')
      return
    }

    // 调用AI生成接口
    const response = await aiApi.generateQuestions({
      subject: '智能组卷',
      topic: paperForm.title || '自动生成试卷',
      question_type: 'mixed',
      difficulty: 'mixed',
      count: totalCount
    })

    if (response.success && response.questions.length > 0) {
      selectedQuestions.value = response.questions.map(q => ({
        id: q.id,
        content: q.content,
        title: q.title,
        question_type: q.question_type,
        difficulty: q.difficulty,
        points: Math.round(paperForm.total_score / totalCount) || 5,
        options: q.options || [],
        tags: q.tags || []
      }))

      ElMessage.success(`成功生成 ${selectedQuestions.value.length} 道题目`)
    }
  } catch (error: any) {
    console.error('智能组卷失败:', error)
    ElMessage.error(error.message || '智能组卷失败')
  } finally {
    generating.value = false
  }
}

// AI优化试卷
const enhancePaper = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请先选择题目')
    return
  }

  try {
    enhancing.value = true
    // TODO: 实现AI优化逻辑
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('试卷优化完成')
  } catch (error) {
    ElMessage.error('优化失败')
  } finally {
    enhancing.value = false
  }
}

// 预览功能
const handlePreview = () => {
  showPreviewDialog.value = true
}

const refreshPreview = () => {
  ElMessage.success('预览已刷新')
}

// 编辑题目
const editQuestion = (question: Question) => {
  router.push(`/questions/questions/${question.id}/edit`)
}

// 保存草稿
const saveDraft = async () => {
  if (!basicFormRef.value) return

  try {
    saving.value = true
    await basicFormRef.value.validate()

    const paperData = {
      ...paperForm,
      status: 'draft',
      questions: selectedQuestions.value.map((q, index) => ({
        question: q.id,
        points: q.points || 5,
        order: index + 1
      }))
    }

    if (isEdit.value) {
      await examPaperApi.updateExamPaper(route.params.id as string, paperData)
    } else {
      await examPaperApi.createExamPaper(paperData)
    }

    ElMessage.success('草稿保存成功')
    router.push('/papers/list')
  } catch (error: any) {
    console.error('Failed to save draft:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 发布试卷
const publishPaper = async () => {
  if (!basicFormRef.value) return

  try {
    await basicFormRef.value.validate()

    if (selectedQuestions.value.length === 0) {
      throw new Error('请选择题目')
    }

    if (Math.abs(currentTotalScore.value - paperForm.total_score) > paperForm.total_score * 0.1) {
      throw new Error('试卷总分与目标分值差距过大')
    }

    saving.value = true

    const paperData = {
      ...paperForm,
      status: 'published',
      questions: selectedQuestions.value.map((q, index) => ({
        question: q.id,
        points: q.points || 5,
        order: index + 1
      }))
    }

    if (isEdit.value) {
      await examPaperApi.updateExamPaper(route.params.id as string, paperData)
    } else {
      await examPaperApi.createExamPaper(paperData)
    }

    ElMessage.success(isEdit.value ? '试卷更新成功' : '试卷发布成功')
    router.push('/papers/list')
  } catch (error: any) {
    console.error('Failed to publish paper:', error)
    ElMessage.error(error.message || '发布失败')
  } finally {
    saving.value = false
  }
}

// 返回
const goBack = () => {
  router.push('/papers/list')
}

// 初始化
onMounted(async () => {
  await loadQuestionBanks()
  await loadQuestions()
})
</script>

<style scoped lang="scss">
.paper-editor {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        color: var(--el-text-color-primary);
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .editor-layout {
    display: grid;
    grid-template-columns: 300px 1fr 350px;
    gap: 24px;
    height: calc(100vh - 180px);
  }

  .config-panel {
    display: flex;
    flex-direction: column;
    gap: 16px;
    overflow-y: auto;

    .el-card {
      .form-unit {
        font-size: 12px;
        color: var(--el-text-color-regular);
        margin-left: 8px;
      }
    }

    .method-option {
      margin-left: 8px;

      .method-title {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .method-desc {
        font-size: 12px;
        color: var(--el-text-color-regular);
        margin-top: 2px;
      }
    }

    .question-stats {
      background: var(--el-fill-color-light);
      padding: 12px;
      border-radius: 6px;

      .stat-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        .stat-label {
          font-size: 12px;
          color: var(--el-text-color-regular);
        }

        .stat-value {
          font-size: 12px;
          font-weight: 500;
          color: var(--el-text-color-primary);
          margin-left: 8px;
        }
      }
    }

    .difficulty-dist {
      .dist-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        span {
          font-size: 12px;
        }
      }
    }
  }

  .question-selector {
    .el-card {
      height: 100%;
      display: flex;
      flex-direction: column;

      .selector-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .question-list {
        flex: 1;
        overflow-y: auto;
        margin-top: 16px;
      }

      .question-item {
        padding: 12px;
        border: 1px solid var(--el-border-color-light);
        border-radius: 6px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          border-color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
        }

        &.selected {
          border-color: var(--el-color-primary);
          background: var(--el-color-primary-light-8);
        }

        .question-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;

          .question-type {
            font-size: 12px;
            padding: 2px 6px;
            background: var(--el-color-info-light-8);
            color: var(--el-color-info);
            border-radius: 3px;
          }

          .question-difficulty {
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 3px;

            &.easy {
              background: var(--el-color-success-light-8);
              color: var(--el-color-success);
            }

            &.medium {
              background: var(--el-color-warning-light-8);
              color: var(--el-color-warning);
            }

            &.hard {
              background: var(--el-color-danger-light-8);
              color: var(--el-color-danger);
            }
          }
        }

        .question-content {
          font-size: 14px;
          color: var(--el-text-color-regular);
          line-height: 1.5;
          margin-bottom: 8px;
        }

        .question-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .question-points {
            font-size: 12px;
            color: var(--el-color-primary);
            font-weight: 500;
          }

          .question-tags {
            display: flex;
            gap: 4px;
          }
        }
      }

      .pagination-wrapper {
        display: flex;
        justify-content: center;
        margin-top: 16px;
      }
    }
  }

  .paper-preview {
    .el-card {
      height: 100%;
      display: flex;
      flex-direction: column;

      .preview-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .paper-content {
        height: 100%;
        display: flex;
        flex-direction: column;
        gap: 16px;
      }

      .paper-info {
        h3 {
          margin: 0 0 8px 0;
          color: var(--el-text-color-primary);
        }

        p {
          margin: 0 0 12px 0;
          color: var(--el-text-color-regular);
          font-size: 14px;
        }

        .paper-meta {
          display: flex;
          gap: 16px;

          .meta-item {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            color: var(--el-text-color-regular);
          }
        }
      }

      .paper-questions {
        flex: 1;
        overflow-y: auto;

        .questions-container {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .paper-question {
          display: flex;
          gap: 12px;
          padding: 12px;
          border: 1px solid var(--el-border-color-light);
          border-radius: 6px;
          background: white;

          .question-number {
            width: 24px;
            font-weight: 500;
            color: var(--el-text-color-primary);
            flex-shrink: 0;
          }

          .question-details {
            flex: 1;

            .question-header-preview {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;

              .question-type {
                font-size: 12px;
                padding: 2px 6px;
                background: var(--el-color-info-light-8);
                color: var(--el-color-info);
                border-radius: 3px;
              }

              .question-actions {
                display: flex;
                gap: 4px;

                .drag-handle {
                  cursor: move;
                  color: var(--el-text-color-placeholder);
                }
              }
            }

            .question-content-preview {
              font-size: 14px;
              color: var(--el-text-color-regular);
              line-height: 1.5;
              margin-bottom: 8px;
            }

            .question-meta-preview {
              display: flex;
              gap: 8px;

              .meta-tag {
                font-size: 12px;
                padding: 2px 6px;
                border-radius: 3px;

                &.difficulty {
                  &.easy {
                    background: var(--el-color-success-light-8);
                    color: var(--el-color-success);
                  }

                  &.medium {
                    background: var(--el-color-warning-light-8);
                    color: var(--el-color-warning);
                  }

                  &.hard {
                    background: var(--el-color-danger-light-8);
                    color: var(--el-color-danger);
                  }
                }

                &.points {
                  background: var(--el-color-primary-light-8);
                  color: var(--el-color-primary);
                }
              }
            }
          }
        }
      }

      .preview-actions {
        margin-top: 16px;
      }
    }
  }

  .preview-dialog-content {
    .preview-paper {
      max-height: 70vh;
      overflow-y: auto;
      padding: 20px;
      background: white;

      .preview-header {
        margin-bottom: 24px;
        text-align: center;

        h2 {
          margin: 0 0 12px 0;
        }

        .preview-description {
          margin: 0 0 16px 0;
          color: var(--el-text-color-regular);
        }

        .preview-instructions {
          text-align: left;
          background: var(--el-fill-color-light);
          padding: 16px;
          border-radius: 6px;

          p {
            margin: 0 0 8px 0;

            strong {
              color: var(--el-text-color-primary);
            }
          }

          ul {
            margin: 0;
            padding-left: 20px;
          }
        }
      }

      .preview-questions {
        .preview-question {
          margin-bottom: 24px;

          .question-title {
            font-weight: 500;
            margin-bottom: 8px;
            color: var(--el-text-color-primary);
          }

          .question-text {
            margin-bottom: 12px;
            line-height: 1.6;
          }

          .question-options {
            .option-item {
              margin-bottom: 6px;
              padding: 4px 0;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .paper-editor {
    .editor-layout {
      grid-template-columns: 280px 1fr 320px;
    }
  }
}

@media (max-width: 1024px) {
  .paper-editor {
    .editor-layout {
      grid-template-columns: 1fr;
      height: auto;

      .config-panel,
      .question-selector,
      .paper-preview {
        height: auto;
        max-height: 400px;
      }
    }
  }
}
</style>
